<template>
  <div class="users-container">
    <div class="header">
      <div class="header-left">
        <h2>用户管理</h2>
        <el-tag type="info" class="user-count">共 {{ (userList || []).length }} 个用户</el-tag>
      </div>
      <div class="header-right">
        <el-button type="success" @click="goToImport" icon="el-icon-upload2">导入用户</el-button>
        <el-button type="primary" @click="showCreateDialog" icon="el-icon-plus">添加用户</el-button>
        <el-button @click="refreshUsers" icon="el-icon-refresh">刷新</el-button>
      </div>
    </div>
    
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="用户名">
            <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="filterForm.email" placeholder="请输入邮箱" clearable></el-input>
          </el-form-item>
          <el-form-item label="注册时间">
            <el-date-picker
              v-model="filterForm.registerTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilter" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetFilter" icon="el-icon-refresh-left">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <el-table 
      :data="paginatedUsers" 
      style="width: 100%" 
      border
      class="users-table"
      v-loading="loading"
    >
      <el-table-column prop="username" label="用户名" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button type="text" @click="goToUserDetail(scope.row.id)">{{ scope.row.username }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="fullName" label="姓名" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="role" label="角色" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.role === 'ADMIN' ? 'danger' : 'info'">
            {{ scope.row.role === 'ADMIN' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="lastLogin" label="最后登录" width="180">
        <template slot-scope="scope">
          {{ scope.row.lastLogin ? formatDateTime(scope.row.lastLogin) : '从未登录' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" @click="showPasswordDialog(scope.row)" icon="el-icon-key">改密</el-button>
          <el-button size="mini" @click="showRoleDialog(scope.row)" icon="el-icon-user">角色</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="(filteredUsers || []).length"
      >
      </el-pagination>
    </div>
    
    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
      class="user-dialog"
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userForm"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="userForm.fullName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="角色" prop="role" v-if="!isEdit">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%;">
            <el-option label="普通用户" value="USER"></el-option>
            <el-option label="管理员" value="ADMIN"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改用户密码"
      :visible.sync="passwordDialogVisible"
      width="500px"
      @close="handlePasswordDialogClose"
      class="password-dialog"
    >
      <el-form
        :model="passwordForm"
        :rules="passwordFormRules"
        ref="passwordForm"
        label-width="100px"
        class="password-form"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmNewPassword">
          <el-input v-model="passwordForm.confirmNewPassword" type="password" placeholder="请确认新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSavePassword">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 角色管理对话框 -->
    <el-dialog
      title="配置用户角色"
      :visible.sync="roleDialogVisible"
      width="500px"
      @close="handleRoleDialogClose"
      class="role-dialog"
    >
      <el-form
        :model="roleForm"
        :rules="roleFormRules"
        ref="roleForm"
        label-width="100px"
        class="role-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="roleForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="roleForm.role" placeholder="请选择角色" style="width: 100%;">
            <el-option label="普通用户" value="USER"></el-option>
            <el-option label="管理员" value="ADMIN"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import moment from 'moment'

export default {
  name: 'Users',
  data() {
    // 密码确认验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (!this.isEdit && value !== this.userForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      dialogVisible: false,
      passwordDialogVisible: false,
      roleDialogVisible: false,
      dialogTitle: '添加用户',
      isEdit: false,
      loading: false,
      filterForm: {
        username: '',
        email: '',
        registerTime: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 20  // 修改默认页面大小为20
      },
      userForm: {
        id: null,
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        fullName: '',
        role: 'USER'
      },
      passwordForm: {
        id: null,
        newPassword: '',
        confirmNewPassword: ''
      },
      roleForm: {
        id: null,
        username: '',
        role: 'USER'
      },
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        fullName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      passwordFormRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        confirmNewPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: this.validateNewPasswordConfirm, trigger: 'blur' }
        ]
      },
      roleFormRules: {
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 重新定义计算属性，避免与data中的属性冲突
    userList() {
      return this.$store.state.users.users || []
    },
    filteredUsers() {
      let result = this.userList;
      
      // 应用过滤条件
      if (this.filterForm.username) {
        result = result.filter(user => 
          user.username.toLowerCase().includes(this.filterForm.username.toLowerCase())
        );
      }
      
      if (this.filterForm.email) {
        result = result.filter(user => 
          user.email.toLowerCase().includes(this.filterForm.email.toLowerCase())
        );
      }
      
      return result;
    },
    paginatedUsers() {
      // 应用分页
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredUsers.slice(start, end);
    }
  },
  async created() {
    await this.refreshUsers();
  },
  methods: {
    ...mapActions('users', ['fetchUsers', 'createUser', 'updateUser', 'deleteUser', 'updateUserPassword', 'updateUserRole']),
    goToUserDetail(userId) {
      this.$router.push(`/users/${userId}`)
    },
    goToImport() {
      this.$router.push('/user-import')
    },
    async refreshUsers() {
      this.loading = true;
      try {
        await this.fetchUsers();
      } catch (error) {
        this.$message.error(error.message || '刷新失败');
      } finally {
        this.loading = false;
      }
    },
    showCreateDialog() {
      this.dialogTitle = '添加用户';
      this.isEdit = false;
      this.userForm = {
        id: null,
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        fullName: '',
        role: 'USER'
      };
      this.dialogVisible = true;
    },
    showEditDialog(user) {
      this.dialogTitle = '编辑用户';
      this.isEdit = true;
      this.userForm = {
        id: user.id,
        username: user.username,
        password: '',
        confirmPassword: '',
        email: user.email,
        fullName: user.fullName
      };
      this.dialogVisible = true;
    },
    showPasswordDialog(user) {
      this.passwordForm = {
        id: user.id,
        newPassword: '',
        confirmNewPassword: ''
      };
      this.passwordDialogVisible = true;
    },
    showRoleDialog(user) {
      this.roleForm = {
        id: user.id,
        username: user.username,
        role: user.role || 'USER'
      };
      this.roleDialogVisible = true;
    },
    validateNewPasswordConfirm(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    handleDialogClose() {
      this.$refs.userForm.resetFields();
    },
    handlePasswordDialogClose() {
      this.$refs.passwordForm.resetFields();
    },
    handleRoleDialogClose() {
      this.$refs.roleForm.resetFields();
    },
    applyFilter() {
      this.pagination.currentPage = 1;
    },
    resetFilter() {
      this.filterForm = {
        username: '',
        email: ''
      };
      this.pagination.currentPage = 1;
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.pagination.currentPage = 1;
    },
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
    },
    async handleSave() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.isEdit) {
              await this.updateUser({
                id: this.userForm.id,
                userData: {
                  email: this.userForm.email,
                  fullName: this.userForm.fullName
                }
              });
              this.$message.success('用户更新成功');
            } else {
              await this.createUser({
                username: this.userForm.username,
                password: this.userForm.password,
                email: this.userForm.email,
                fullName: this.userForm.fullName,
                role: this.userForm.role
              });
              this.$message.success('用户创建成功');
            }
            this.dialogVisible = false;
            await this.refreshUsers();
          } catch (error) {
            this.$message.error(error.message || '操作失败');
          }
        }
      });
    },
    async handleSavePassword() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (valid) {
          try {
            await this.updateUserPassword({
              id: this.passwordForm.id,
              newPassword: this.passwordForm.newPassword
            });
            this.$message.success('密码更新成功');
            this.passwordDialogVisible = false;
            await this.refreshUsers();
          } catch (error) {
            this.$message.error(error.message || '操作失败');
          }
        }
      });
    },
    async handleSaveRole() {
      this.$refs.roleForm.validate(async (valid) => {
        if (valid) {
          try {
            await this.updateUserRole({
              id: this.roleForm.id,
              role: this.roleForm.role
            });
            this.$message.success('角色更新成功');
            this.roleDialogVisible = false;
            await this.refreshUsers();
          } catch (error) {
            this.$message.error(error.message || '操作失败');
          }
        }
      });
    },
    async handleDelete(user) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.deleteUser(user.id);
          this.$message.success('删除成功');
          await this.refreshUsers();
        } catch (error) {
          this.$message.error(error.message || '删除失败');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    formatDateTime(datetime) {
      return datetime ? moment(datetime).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    goToUserDetail(userId) {
      this.$router.push({ name: 'UserDetail', params: { id: userId } });
    },
    goToImport() {
      this.$router.push({ name: 'UserImport' });
    }
  }
}
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.user-count {
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.filter-content {
  padding: 20px 0;
}

.filter-form ::v-deep .el-form-item {
  margin-bottom: 0;
}

.users-table {
  margin-bottom: 20px;
}

.users-table ::v-deep .el-table__row:hover {
  background-color: #f5f7fa;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.user-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.user-form ::v-deep .el-form-item {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-left {
    justify-content: center;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .filter-content {
    padding: 15px 0;
  }
  
  .filter-form ::v-deep .el-form-item {
    margin-bottom: 15px;
    width: 100%;
  }
  
  .filter-form ::v-deep .el-form-item__content {
    width: 100%;
  }
  
  .filter-form ::v-deep .el-input,
  .filter-form ::v-deep .el-select {
    width: 100% !important;
  }
}
</style>